package com.sz.controller;

import com.sz.constant.MessageConstant;
import com.sz.entity.Result;
import com.sz.pojo.Setmeal;
import com.sz.service.SetmealService;
import com.sz.utils.QiNiuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile) {
        //获取文件名
        String originalFilename = imgFile.getOriginalFilename();
        //截取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成唯一文件名拼接后缀
        String filename = UUID.randomUUID().toString() + suffix;
        try {
            //调用QiNiuUtils上传
            QiNiuUtils.uploadViaByte(imgFile.getBytes(), filename);
            //返回结果给前端
            //构造返回数据
            Map<String, String> resultMap = new HashMap<String, String>();
            resultMap.put("imgName", filename);
            resultMap.put("domain", QiNiuUtils.DOMAIN);
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal, @RequestParam List<Integer> checkgroupIds) {
        setmealService.add(setmeal, checkgroupIds);
        return new Result(true, MessageConstant.ADD_CHECKGROUP_SUCCESS);
    }

}
